//
//  ColorCell.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/17.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit
import SCLAlertView
import Kingfisher

protocol ColorCellDelegate: class {
    func insertColor(color: CodableColorOfMaterial)
    func deleteColor(at index: Int)
}


struct ColorOfMaterial {
    var no: String
    var color: String
    var strock: Int
}

class ColorCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
    
    var items = [ColorOfMaterial]()
    var images = [Any]()
    var edited = true {
        didSet {
            if edited == false {
                constraint.constant = 8
            }
        }
    }
    
    
    weak var delegate: ColorCellDelegate?
    
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var addButton: UIButton!
    @IBOutlet weak var constraint: NSLayoutConstraint!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UINib(nibName: "ColorInsideCell", bundle: nil), forCellWithReuseIdentifier: "ColorInsideCell")
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return items.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let row = indexPath.row
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ColorInsideCell", for: indexPath) as! ColorInsideCell
        cell.noLabel.text = items[row].no
        cell.colorLabel.text = items[row].color
        cell.stockLabel.text = "\(items[row].strock)"
        if let image = images[row] as? UIImage {
            cell.imageView.image = image
        } else {
            if let url = URL(string: (images[row] as! String)) {
                cell.imageView.kf.setImage(with: url)
            }
        }
        cell.deleteButton.isHidden = !edited
        cell.deleteButton.addTarget(self, action: #selector(deleteBtTapped(_:)), for: .touchUpInside)
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
    }
    @objc func deleteBtTapped(_ button: UIButton!) {
        let point = button.convert(CGPoint.zero, to: collectionView)
        guard let indexPath = collectionView.indexPathForItem(at: point) else {
            return
        }
        print(items)
        items.remove(at: indexPath.row)
        images.remove(at: indexPath.row)
        delegate?.deleteColor(at: indexPath.row)
        collectionView.performBatchUpdates({
            collectionView.deleteItems(at: [indexPath])
        }, completion: nil)
    }
    
    func showAlert(image: UIImage) {
        let appearance = SCLAlertView.SCLAppearance(showCloseButton: false, shouldAutoDismiss: true, hideWhenBackgroundViewIsTapped: true)
        let alert = SCLAlertView(appearance: appearance)
        let numberTF = alert.addTextField("颜色编号")
        numberTF.keyboardType = .numberPad
        let colorTF = alert.addTextField("颜色")
        let kucunTF = alert.addTextField("库存")
        kucunTF.keyboardType = .numberPad
        alert.showEdit("设置色板信息", subTitle: "")
        alert.addButton("确认") {
            guard let number = numberTF.text.nilIfEmpty, let colorText = colorTF.text.nilIfEmpty, let kucun = kucunTF.text.nilIfEmpty else {
                return
            }
            let color = ColorOfMaterial(no: number, color: colorText, strock: Int(kucun)!)
            self.items.append(color)
            self.images.append(image)
            let base64 = self.convertToBase64(image)!
            self.delegate?.insertColor(color: CodableColorOfMaterial(no: color.no, color: color.color, stock: color.strock, picture: base64))
            self.collectionView.performBatchUpdates({
                self.collectionView.insertItems(at: [IndexPath(row: self.items.count-1, section: 0)])
            }, completion: nil)
        }
    }
}
